<template>
  <div class="app-container">
    <el-button
      class="collapesbutton"
      type="primary"
      plain
      style="left: 0; height: 10%"
      @click="handleShow(1)"
      v-if="!show1"
      ><i :class="show1 ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"></i
    ></el-button>
    <el-button
      class="collapesbutton"
      type="info"
      plain
      style="left: 14px; height: 5%"
      @click="handleShow(2)"
      v-if="!show1 && !show2"
      ><i :class="show2 ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"></i
    ></el-button>
    <el-row
      :style="
        'height: 100%;margin-left:' +
        (show1 ? 0 : show2 ? '14px' : '28px') +
        ';margin-right:' +
        (show1 ? 0 : show2 ? '14px;' : '28px;')
      "
    >
      <el-col
        v-if="show1"
        :span="3"
        :xs="24"
        class="treeMenu"
        style="background: #fff; positon: relative"
      >
        <el-button
          class="collapesbutton"
          type="primary"
          plain
          style="right: 1px; height: 10%"
          @click="handleShow(1)"
          v-if="show1"
          ><i
            :class="show1 ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"
          ></i
        ></el-button>
        <el-button
          class="collapesbutton"
          type="info"
          plain
          style="right: -14px; height: 5%"
          @click="handleShow(2)"
          v-if="show1 && !show2"
          ><i
            :class="show2 ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"
          ></i
        ></el-button>
        <div class="head-container" style="border-right: 1px solid #dcdfe6">
          <el-input
            v-model="keyword"
            placeholder="请输入关键字"
            clearable
            size="small"
            prefix-icon="el-icon-search"
            style="margin: 10px 0; width: 100%; hegith: 80%"
          />
          <el-menu :default-active="activeIndex" class="el-menu-vertical">
            <el-menu-item
              v-for="(item, i) in showMenuData"
              :key="i"
              :index="i.toString()"
              @click="handleOpen(item)"
            >
              <i :class="item.icon"></i>
              <span
                slot="title"
                v-html="item.description"
                :title="item.description"
              ></span>
            </el-menu-item>
          </el-menu>
        </div>
      </el-col>
      <el-col v-if="show2" :span="2" :xs="24" class="treeMenu">
        <el-button
          class="collapesbutton"
          type="info"
          plain
          style="right: 0; height: 5%"
          @click="handleShow(2)"
          ><i
            :class="show2 ? 'el-icon-d-arrow-left' : 'el-icon-d-arrow-right'"
          ></i
        ></el-button>
        <div class="head-container">
          <div
            style="
              margin: 10px 0;
              text-align: center;
              height: 32px;
              line-height: 32px;
            "
          >
            策略状态
          </div>
          <el-menu :default-active="subActiveIndex" class="el-menu-vertical">
            <el-menu-item
              v-for="(item, i) in subMenuData"
              :key="i"
              :index="i.toString()"
              @click="handleOpenSub(item)"
            >
              <i :class="item.icon"></i>
              <span
                slot="title"
                v-html="item.description"
                :title="item.description"
              ></span>
            </el-menu-item>
          </el-menu>
        </div>
      </el-col>
      <el-col
        :span="show1 ? (show2 ? 19 : 21) : show2 ? 22 : 24"
        :xs="24"
        style="padding: 10px 10px 0; height: 100%"
      >
        <div class="mainContent">
          <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
              <el-button type="primary" size="mini" @click="handleAdd">添加角色 </el-button>
              <el-button type="info" size="mini" @click="handleDel">移除角色 </el-button>
              <el-button type="primary" size="mini" @click="handleAddAttre" :disabled="hasQuality"
                >添加属性
              </el-button>
              <el-button type="info" size="mini" @click="handleDelAttre" :disabled="!hasQuality"
                >移除属性
              </el-button>
              <el-button type="primary" size="mini" @click="handleSub">保存更改 </el-button>
              <el-button type="primary" size="mini" @click="getAuths()">重置 </el-button>
            </el-col>
          </el-row>
          <el-table
            :data="list"
            v-loading="loading"
            :height="maxHeight"
            style="width: 100%"
            :header-cell-style="{ background: '#F6F8FB' }"
            border
            stripe
            @selection-change="handleSelectionChange"
            v-scrollbar="'.el-table__body-wrapper'"
          >
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column
              prop="roleName"
              label="角色"
              width="180"
              align="center"
            >
            </el-table-column>
            <el-table-column
              prop="attribute"
              label="属性"
              width="180"
              align="center"
              v-if="hasQuality"
            >
              <template slot-scope="scope">
                {{dataFormat('attrList',scope.row.attribute)}}
              </template>
            </el-table-column>
            <el-table-column
              prop="attributeValue"
              label="属性值"
              width=""
              align="center"
              v-if="hasQuality"
            >
              <template slot-scope="scope">
                {{dataFormat(scope.row.attribute,scope.row.attributeValue)}}
              </template>
            </el-table-column>
            <el-table-column prop="read" label="查看" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.read"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="modify" label="修改" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.modify"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="remove" label="删除" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.remove"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="created" label="创建" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.created"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="release" label="发布" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.release"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="revise" label="换版" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.revise"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="obsolete" label="作废" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.obsolete"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="views" label="浏览" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.views"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="checkIn" label="上传" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.checkIn"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="download" label="下载" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.download"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="promote" label="升级" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.promote"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="demote" label="降级" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.demote"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="subordinate" label="查看下级" align="center">
              <template slot-scope="scope">
                <el-checkbox v-model="scope.row.subordinate"></el-checkbox>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-col>
    </el-row>
    <!-- 添加角色 -->
    <el-dialog
      ref="formTable"
      :title="title"
      :visible.sync="topen"
      v-if="topen"
      width="50%"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form
        :inline="true"
        :model="queryParams"
        ref="queryForm"
        label-width="100"
        style="float: right"
        @submit.native.prevent
      >
        <el-form-item
          label="关键字"
        >
          <el-input
            size="small"
            v-model="queryParams['key']"
            placeholder='请输入关键字'
            clearable
            @keyup.enter.native="handleQuery"
          >
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            v-preventReClick
            @click="handleQuery"
            >搜索
          </el-button>
          <el-button
            type="info"
            icon="el-icon-refresh"
            size="mini"
            v-preventReClick
            @click="resetQuery"
            >重置
          </el-button>
        </el-form-item>
      </el-form>
      <el-table
        v-loading="loading"
        :data="formTableList"
        height="480px"
        stripe
        @selection-change="handleSelectionrole"
        v-scrollbar="'.el-table__body-wrapper'"
        :header-cell-style="{ background: '#F6F8FB' }"
      >
        <el-table-column type="selection" width="50" align="center" />
        <el-table-column label="角色名称" align="center" prop="roleName" />
        <el-table-column label="权限字符" align="center" prop="roleKey" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitRoleForm">确 定</el-button>
        <el-button @click="cancelRole">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加属性 -->
    <el-dialog
      ref="attrForm"
      :title="title"
      :visible.sync="aopen"
      v-if="aopen"
      width="30%"
      v-dialogDrag
      :close-on-click-modal="false"
    >
      <el-form>
        <el-form-item label="属性选择" required>
          <el-select v-model="attribute">
            <el-option v-for="dict of attrList" :value="dict.dictValue" :label="dict.dictLabel" :key="dict.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitAttrForm">确 定</el-button>
        <el-button @click="cancelAttr">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import dynamicSearchForm from "@/views/components/dynamicSearchForm";
import dynamicTable from "@/views/components/dynamicTable";
import dynamicForm from "@/views/components/dynamicForm";
import { policyList, listState } from "@/api/pms/policy";
import { listRole } from "@/api/system/role";
import { listAuth, updateAuth, delAuth } from "@/api/system/authority";
import dynamicTree from "../../components/dynamicTree.vue";
import { deepClone, filter2sub } from "@/utils";

export default {
  inject: ['app'],
  components: {
    dynamicSearchForm,
    dynamicForm,
    dynamicTable,
    dynamicTree,
  },
  data() {
    return {
      activeName: "menuData",
      activeIndex: "0",
      subActiveIndex: "0",
      // 遮罩层
      // 加载层信息
      loading: false,
      show1: true,
      show2: true,
      toolbarData: [],
      list: [],
      policyId: "",
      policyStateId: "",
      showMenuData: [],
      menuData: [],
      subMenuData: [],
      keyword: "",
      queryParams:{
        key: ''
      },
      hasQuality: false,
      attrList: [],
      attribute: "",
      rolesById: {},
      // 角色添加表单
      topen: false,
      // 属性添加表单
      aopen: false,
      title: "",
      authIds: [],
      roleIds: [],
      hasRoles: [],
      formTableList: [],
      copy_formTableList: [],
      defaultAuth: {
        attribute: "",
        attributeValue: "",
        see: false,
        modify: false,
        remove: false,
        found: false,
        release: false,
        versionChange: false,
        toVoid: false,
        browse: false,
        uploads: false,
        download: false,
        upgrade: false,
        demotion: false,
        seeSubordinate: false,
      },
    };
  },
  created() {
    this.getMenuList();
    this.getRoles();
    this.getDicts('attrList').then(response=>{
      this.tempDicts['attrList'] = deepClone(response.data);
      for(let item of response.data){
        this.getDicts(item.dictValue).then(response=>{
          this.tempDicts[item.dictValue] = deepClone(response.data)
        })
      }
    })
  },
  watch: {
    keyword(val) {
      this.showMenuData = this.menuData.filter((item) => {
        if (!val) {
          this.showMenuData = this.menuData.slice();
          return true;
        }
        if (item.description.match(new RegExp(val, "gi"))) {
          return item;
        }
      });
    },
  },
    computed: {
      maxHeight(){
        return this.app.screenHeight - 200
      },
    },
  methods: {
    /** 获取列表数据 */
    getMenuList() {
      this.loading = true;
      policyList().then((response) => {
        this.menuData = response.rows;
        this.showMenuData = this.menuData.slice();
        this.handleOpen(this.showMenuData[0]);
        this.loading = false;
      });
    },
    handleOpen(item) {
      this.policyId = "";
      this.policyId = item.id;
      this.getSubMenu(this.policyId);
    },
    /** 获取配置信息 */
    getSubMenu(id) {
      // this.loading = true;
      listState({ policyid: id }).then((response) => {
        this.subMenuData = response.rows;
        this.handleOpenSub(this.subMenuData[0]);
        this.loading = false;
      });
    },
    /** 获取角色数据 */
    getRoles() {
      listRole().then((response) => {
        // this.list = response.rows;
        for (let row of response.rows) {
          this.rolesById[row.roleId] = row;
        }
      });
    },
    // 节点单击事件
    handleOpenSub(item) {
      this.policyStateId = "";
      this.policyStateId = item.id;
      this.getAuths();
    },
    // 获取权限数据
    getAuths() {
      this.loading = true;
      this.attribute = ''
      this.hasQuality = false
      listAuth({
        policyId: this.policyId,
        policyStateId: this.policyStateId,
      }).then((response) => {
        // this.list = response.rows;
        this.list = [];
        this.hasRoles = [];
        if (response.rows.length > 0) {
          for (let row of response.rows) {
            if (!this.hasQuality && row.attribute) {
              this.hasQuality = true;
              this.attribute = row.attribute
            }
            row.roleName = this.rolesById[row.roleId].roleName;
            if (this.hasRoles.indexOf(row.roleId) == -1)
              this.hasRoles.push(row.roleId);
            this.list.push(row);
          }
        }
        this.loading = false;
      });
    },
    // 显示隐藏侧边
    handleShow(code) {
      if (code == 1) {
        this.show1 = !this.show1;
      }
      if (code == 2) {
        this.show2 = !this.show2;
      }
    },
    // 权限列表多选
    handleSelectionChange(val) {
      this.authIds = val.map((item) => {
        return item.roleId;
      });
    },
    // 添加角色
    handleAdd() {
      this.title = "添加角色";
      this.formTableList = [];
      for (let i in this.rolesById) {
        if (this.hasRoles.indexOf(Number(i)) == -1)
          this.formTableList.push(this.rolesById[i]);
      }
      this.copy_formTableList = deepClone(this.formTableList)
      this.topen = true;
    },
    handleQuery(){
      this.formTableList = this.formTableList.filter(item=>{
        return item.roleName.indexOf(this.queryParams.key)>-1 || item.roleKey.indexOf(this.queryParams.key)>-1
      })
    },
    resetQuery(){
      this.queryParams={key:''}
      this.formTableList = deepClone(this.copy_formTableList)
    },
    // 移除角色
    handleDel() {
      this.title = "移除角色";
      this.formTableList = [];
      for (let i in this.rolesById) {
        if (this.hasRoles.indexOf(Number(i)) > -1)
          this.formTableList.push(this.rolesById[i]);
      }
      this.topen = true;
    },
    // 保存更改
    handleSub() {
      updateAuth(this.list).then((response) => {
        if (response.code == 200) {
          this.msgSuccess(response.msg);
          this.getAuths();
        } else {
          this.msgError(response.msg);
          this.getAuths();
        }
      });
    },
    // 表格表单数据提交
    submitRoleForm() {
      if (this.title == "添加角色") {
        for (let i of this.roleIds) {
          let newLi = {
            policyId: this.policyId,
            policyStateId: this.policyStateId,
            roleId: i,
            roleName: this.rolesById[i].roleName,
            ...this.defaultAuth,
          };
          this.list.push(newLi);
        }
        this.topen = false;
      } else if (this.title == "移除角色") {
        this.authIds = [];
        for (let item of this.list) {
          if (this.roleIds.indexOf(item.roleId) > -1 && item.id) {
            this.authIds.push(item.id);
          }
        }
        this.topen = false;
        this.$confirm(
          '是否确认移除角色编号为"' + this.roleIds + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            return delAuth(this.authIds);
          })
          .then((response) => {
            this.getAuths();
            this.msgSuccess(response.msg);
          })
          .catch(function () {});
      }
    },
    // 取消表单
    cancelRole() {
      this.topen = false;
    },
    // 表格表单多选
    handleSelectionrole(val) {
      this.roleIds = val.map((item) => {
        return item.roleId;
      });
    },
    handleAddAttre() {
      this.aopen=true
      this.title = '添加属性'
      this.getDicts('attrList').then(response=>{
        this.tempDicts['attrList'] = deepClone(response.data);
        this.attrList = response.data
      })
    },
    handleDelAttre() {
      this.getDicts(this.attribute).then(response=>{
        this.attribute = ''
        this.attrList = response.data
      })
      this.title = '请选择保留原权限的属性值'
      this.aopen = true
      // for(let item of this)
    },
    cancelAttr() {
      this.aopen = false
      this.attribute = ''
    },
    submitAttrForm() {
      var newList = []
      if(this.title == '添加属性'){
        if(this.attribute) {
          this.getDicts(this.attribute).then((response) => {
            this.tempDicts[this.attribute] = deepClone(response.data);
            for(let item of this.list) {
              for(let index in response.data){
                let dict = response.data[index]
                let li = {
                  policyId: this.policyId,
                  policyStateId: this.policyStateId,
                  roleId: item.roleId,
                  roleName: item.roleName,
                  ...this.defaultAuth,
                }
                if(index == 0) li.id = item.id
                li.attribute = dict.dictType
                li.attributeValue = dict.dictValue
                newList.push(li)
              }
            }
            this.list = newList
            this.hasQuality = true
          });
        }
      }else{
        this.authIds = [];
        this.list = this.list.filter(item=>{
          if(item.attributeValue == this.attribute){
            item.attribute = ''
            item.attributeValue = ''
            return item
          }else{
            this.authIds.push(item.id)
          }
        })
        this.attribute = ''
        this.hasQuality = false
        delAuth(this.authIds)
        this.handleSub()
      }
      this.aopen = false
    },
  },
};
</script>
<style lang="scss" scoped>
.app-container {
  padding: 0;
  margin: 0;
  position: relative;
}
.collapesbutton {
  width: 14px;
  position: absolute;
  top: 0;
  bottom: 0;
  padding: 0;
  border: none;
  margin: auto 0;
  z-index: 200;
}
.treeMenu {
  background-color: #f8f8f8;
  height: 100%;
  position: relative;
}
.el-menu-item {
  border-bottom: 1px solid #dcdfe6;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
// .el-menu-vertical{
//   height: 100%;
// }
.app-container .head-container {
  padding-left: 5px;
  padding-right: 5px;
  border-top: 1px solid #d8d8d8;
  height: 100%;
  overflow-y: auto;
  .el-menu {
    background: rgba(0, 0, 0, 0) !important;
  }
}

.el-tabs__item {
  height: 30px;
  line-height: 30px;
}

.page-title {
  background: #fff;
  border: 1px solid #d8d8d8;
  overflow: hidden;
  text-overflow: ellipsis;
  vertical-align: middle;
  white-space: nowrap;
  /*margin-bottom: 5px;*/
}

.headerContent {
  float: left;
  padding: 20px 0 10px;
  width: 100%;
}

.extendedHeader {
  display: block;
  line-height: 23px;
  white-space: nowrap;
}

.extendedHeader.name {
  font-size: 16px;
  font-weight: bold;
  font-family: "3dsregular", Arial, Helvetica, sans-serif;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.extendedHeader.content {
  font-size: 13px;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.extendedHeader.fromTitle {
  font-size: 13px;
  width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.flex {
  display: flex;
}
.el-col-21[data-v-0e4055ba] {
  width: 87.5%;
}
.infinite-list {
  list-style: none;
  padding: 5px;
  margin: 0;
}

.infinite-list-item {
  list-style: none;
  padding: 5px;
  margin: 0;
  background-color: #f8f8f8;
  border-bottom: 1px solid #d8d8d8;
  position: relative;
}

.infinite-list-item.selected {
  list-style: none;
  padding: 5px;
  margin: 0;
  background-color: #fff;
  border-bottom: 1px solid #d8d8d8;
  position: relative;
}

.el-dropdown {
  padding: 10px;
  border-right: 1px solid #c3c3c3;
}

.mainContent {
  float: left;
  width: 100%;
  padding: 0 4px 0 5px;
  height: 100%;
}

.extendedMain {
  display: block;
  line-height: 23px;
  white-space: nowrap;
}

.extendedMain.name {
  font-size: 16px;
  font-weight: bold;
  font-family: "3dsregular", Arial, Helvetica, sans-serif;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.extendedMain.content {
  font-size: 13px;
  max-width: 250px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0 5px 10px;
}

.extendedMain.fromTitle {
  font-size: 13px;
  width: 150px;
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
  padding: 5px 0 5px 10px;
  background-color: #f8f8f8;
}
.el-tree {
  //padding: 10px;
  // font-size: 14px;
  background-color: #f8f8f8;
}
//去掉最上级的before  after 即是去电最上层的连接线
/deep/ .el-tree > div {
  &::before {
    display: none;
  }
  &::after {
    display: none;
  }
}
.el-col-21 {
  width: 86%;
  float: right;
}
</style>
